2 - Functions in JavaScript

Introducing Functions

Programming is similar to baking cakes. Seriously! Imagine you are trying to teach your friend Jane how to bake many different types of cakes.

Each cake takes in different ingredients (ie. inputs). But the 'bake' instructions are always the same. For example:

  1. Pre-heat the oven at 300 degrees
  2. Mix all the ingredients in a bowl
  3. Put contents into oven for 30 mins

And the output will be a different cake each time.

It is tedious to have to repeat to Jane the same 'bake' instructions every time. What if we could just say 'bake' and Jane would know to execute those three steps? That is exactly what a function is!

// This is what a function looks like:
var divideByThree = function (number) {
    var val = number / 3;
    console.log(val);
};
// On line 12, we call the function by name
// Here, it is called 'dividebythree'
// We tell the computer what the number input is (i.e. 6)
// The computer then runs the code inside the function!
divideByThree(6);
Function syntax

A function takes in inputs, does something with them, and produces an output.

Here's an example of a function:

var sayHello = function(name) {
    console.log('Hello ' + name);
};

First we declare a function using var, and then give it a name sayHello. The name should begin with a lowercase letter and the convention is to use lowerCamelCase where each word (except the first) begins with a capital letter.
Then we use the function keyword to tell the computer that you are making a function
The code in the parentheses is called a parameter. It's a placeholder word that we give a specific value when we call the function. Click "Stuck? Get a hint!" for more.
Then write your block of reusable code between { }. Every line of code in this block must end with a ;.
You can run this code by "calling" the function, like this:
sayHello("Emily");
Calling this function will print out Hello Emily.
var greeting = function (name) {
    console.log("Great to see you," + " " + name);
};
// On line 11, call the greeting function!
greeting("Jesse");
var foodDemand = function(food){
    console.log("I want to eat" + " " + food);
}
foodDemand("Pizza");
// Nicely written function:
var calculate = function (number) {
    var val = number * 10;
    console.log(val);
};
var greeting = function(name) {
    console.log(name);
} 
greeting("Hello");
Return keyword

Nice job! Now, when we call a function, we don't always want to just print stuff. Sometimes, we just want it to return a value. We can then use that value (ie. the output from the function) in other code. Let's learn about the return keyword, then we'll see how to use functions with an if / else statement in the next exercise!

The return keyword simply gives the programmer back the value that comes out of the function. So the function runs, and when the return keyword is used, the function will immediately stop running and return the value.

// Parameter is a number, and we do math with that parameter
var timesTwo = function(number) {
    return number * 2;
};
// Call timesTwo here!
var newNumber = timesTwo(5);
console.log(newNumber);
Functions, return and if / else

When we call a function, its return value is just the result from running the function. That value can then be used just like any other value in JavaScript!

Look at the if statement starting on line 7. The if statement is checking whether the result of calling the function namedquarter is divisible by 3.

// Define quarter here.
var quarter = function(number){
    return number/4;
}
if (quarter(12) % 3 === 0 ) {
  console.log("The statement is true");
} else {
  console.log("The statement is false");
}
Functions with two parameters

So far we've only looked at functions with one parameter. But often it is useful to write functions with more than one parameter. For example, we can have the following function:

var areaBox = function(lengthwidth) {
    return length * width;
};
 With more than one parameter, we can create more useful functions

To call a function with more than one parameter, just enter a value for each parameter in the parentheses. For example, areaBox(3,9); would return the area of a box with a length of 3 and a width of 9.

// Write your function starting on line 3
var perimeterBox = function(lengthwidth){
    return (length + length + width + width);
}
perimeterBox(20, 40);
Global vs Local Variables

Let's talk about an important concept: scope. Scope can be global or local.

Variables defined outside a function are accessible anywhere once they have been declared. They are called global variables and their scope is global.

var globalVar = "hello";
var foo = function() {
    console.log(globalVar);  // prints "hello"
}

The variable globalVar can be accessed anywhere, even inside the function foo.

Variables defined inside a function arelocal variables. They cannot be accessed outside of that function.

var bar = function() {
    var localVar = "howdy";
}
console.log(localVar);  // error

The variable localVar only exists inside the function bar. Trying to printlocalVar outside the function gives a error.

Check out the code in the editor. Until now you've been using the var keyword without really understanding why. Thevar keyword creates a new variable in the current scope. That means if var is used outside a function, that variable has a global scope. If var is used inside a function, that variable has a local scope.

On line 4 we have not used the varkeyword, so when we log my_number to the console outside of the function, it will be 14.

var my_number = 7; //this has global scope
var timesTwo = function(number) {
    var my_number = number * 2;
    console.log("Inside the function my_number is: ");
    console.log(my_number);
}; 
timesTwo(7);
console.log("Outside the function my_number is: ")
console.log(my_number);
Functions & if / else

An especially useful application of reusable code is if/else statements. These can be very wordy, and a pain to type repeatedly.

We are going to write a function that checks how many hours of sleep a night you're getting. Inside the function will be an if/else statement. We want the function to check many different numbers of hours to see whether a person is getting enough sleep.

// Write your function below. 
// Don't forget to call your function!
var sleepCheck = function(numHours){
    if (numHours >= 8){
        return("You're getting plenty of sleep! Maybe even too much!");
    }
    else
    {
        return("Get some more shut eye!");
    }
}
sleepCheck(10);
sleepCheck(5);
sleepCheck(8);
The Game

Rock paper scissors is a classic 2 player game. Each player chooses either rock, paper or scissors. The possible outcomes:

  • Rock destroys scissors.
  • Scissors cut paper.
  • Paper covers rock.

Our code will break the game into 3 phases:
a. User makes a choice
b. Computer makes a choice
c. A compare function will determine who wins

User Choice

We start by first asking the user which option they want to pick. We will later use this choice in the compare function to determine the winner.

Computer Choice: Part 1

Awesome! We now need the computer to make a choice. The game is only going to be fun if the computer chooses randomly. Luckily JavaScript has something that can help with this.

If we declare a variable and make it equal to Math.random(), that variable will equal a number between 0 and 1.

Computer Choice: Part 2

We have computerChoice but it now equals a random number between 0 and 1. We need to somehow translate this random number into a random choice of rock, paper, or scissors. How do we do this?!

  1. If computerChoice is between 0 and 0.33, make computerChoice equal to"rock".
  2. If computerChoice is between 0.34 and 0.66, make computerChoice equal to"paper".
  3. If computerChoice is between 0.67 and 1, make computerChoice equal to"scissors".

But there are three outcomes! Using ifelse only lets us have two outcomes. What now?! We need to use if / elseif / else. See the hint for the full syntax. You will laugh at how easy it is.

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
console.log(computerChoice);
if (computerChoice < 0.33){
    computerChoice = "rock";
} 
else{
    if (computerChoice < 0.66){
        computerChoice = "paper";
    }
    else{
        computerChoice = "scissors";
    }
}
console.log(computerChoice);
Both choices are the same!

Now comes the fun part! We need to create a function. It will take two parameters (ie. the two choices made) and then return the winning choice.

When programming a game like this, you have to first figure out all the various outcomes. One outcome is that the choice the user makes is equal to the choice the computer makes.

/*var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
    computerChoice = "rock";
} else if(computerChoice <= 0.67) {
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
} console.log("Computer: " + computerChoice);*/
var compare = function(choice1choice2){
    if(choice1 == choice2){
        return "The result is a tie!";
    }
}
What if choice1 is rock?

You're doing great! Now we consider the other scenarios. Let's break the problem down a little. What if choice1 is "rock"? Given choice1 is "rock",

a. if choice2 === "scissors", then"rock" wins.
b. if choice2 === "paper", then "paper"wins.

How do we structure this? It's a bit different from what we have already seen. We will first have an if statement. And then the code inside that ifstatement will be... another ifstatement!

/*var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
    computerChoice = "rock";
} else if(computerChoice <= 0.67) {
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
} console.log("Computer: " + computerChoice);*/
var compare = function(choice1choice2){
    if(choice1 == choice2){
        return "The result is a tie!";
    }
    else if(choice1 == "rock"){
        if(choice2 == "scissors"){
            return "rock wins";
        }
        else{
            return "paper wins";
        }
    }
}
What if choice1 is paper?

Now what if choice1 is "paper"? Given choice1 is "paper",

a. if choice2 === "rock", then "paper"wins.
b. if choice2 === "scissors", then"scissors" wins.

/*var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
    computerChoice = "rock";
} else if(computerChoice <= 0.67) {
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
} console.log("Computer: " + computerChoice);*/
var compare = function(choice1choice2){
    if(choice1 == choice2){
        return "The result is a tie!";
    }
    else if(choice1 == "rock"){
        if(choice2 == "scissors"){
            return "rock wins";
        }
        else{
            return "paper wins";
        }
    }
    else if(choice1 = "paper"){
        if(choice2 == "rock"){
            return "paper wins";
        }
        else{
            return "scissors wins";
        }
    }
}
What if choice1 is scissors?

Lastly, what if choice1 is "scissors"? Given choice1 is "scissors",

a. if choice2 === "rock", then "rock"wins.
b. if choice2 === "paper", then"scissors" wins.

var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
    computerChoice = "rock";
} else if(computerChoice <= 0.67) {
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
} console.log("Computer: " + computerChoice);
var compare = function(choice1choice2){
    if(choice1 == choice2){
        return "The result is a tie!";
    }
    else if(choice1 == "rock"){
        if(choice2 == "scissors"){
            return "rock wins";
        }
        else{
            return "paper wins";
        }
    }
    else if(choice1 == "paper"){
        if(choice2 == "rock"){
            return "paper wins";
        }
        else{
            return "scissors wins";
        }
    }
}
compare(userChoice, computerChoice);